from django.shortcuts import render
from django.http import JsonResponse,HttpResponse
from django.views import View
from django_redis import get_redis_connection
from meiduo_mall.libs.captcha.captcha import captcha
import re,random
from celery_tasks.sms.tasks import ccp_send_sms_code
import logging
logger = logging.getLogger('django')
#Create your views here.



class ImageCodeView(View):
    def get(self,request,uuid):
        if not re.match(r'^\w{8}(-\w{4}){3}-\w{12}$',uuid):
            return JsonResponse({
                'code':400,
                'errmsg':'uuid不符合格式!'
            })

        text,image = captcha.generate_captcha()
        print("图形验证码:",text)
        conn = get_redis_connection('verify_code')
        try:
            conn.setex(
                "img_%s"%uuid,
                300,
                text
            )
        except Exception as e:
            return JsonResponse({
                'code':400,
                'errmsg':'验证码保存失败!'
            })
        return HttpResponse(image,content_type='image/jpg')

class SMSCodeView(View):
    def get(self,request,mobile):
        image_code = request.GET.get('image_code')
        image_code_id = request.GET.get('image_code_id')

        if not all([image_code,image_code_id]):
            return JsonResponse({
                'code':400,
                'errmsg':'参数错误!'
            })

        conn = get_redis_connection('verify_code')
        image_code_from_redis = conn.get('img_%s'%image_code_id)
        if not image_code_from_redis:
            return JsonResponse({
                'code':400,
                'errmsg':'图形验证码过期!'
            })
        if image_code.lower() != image_code_from_redis.decode().lower():
            return JsonResponse({
                'code':400,
                'errmsg':'验证码输入有误!'
            })
        conn.delete('img_%s'%image_code_id)

        flag = conn.get("sms_flag_%s"%mobile)
        if flag:
            return JsonResponse({
                'code':400,
                'errmsg':'操作频率过快!'
            })

        sms_code = "%06d" % random.randint(0,999999)
        print("手机验证码:" ,sms_code)
        p = conn.pipeline()
        try:
            p.setex("sms_%s"%mobile,300,sms_code)
            p.setex("sms_flag_%s"%mobile,60,'-1')
            p.execute()  # 通过管道批量执行redis指令
        except Exception as e:
            logger.info(e)
            return JsonResponse({
                'code': 400,
                'errmsg': 'redis数据库访问失败！'
            })

        # 2.3 调用云通讯发送短信
        # CCP().send_template_sms(mobile, [sms_code, 5], 1)
        ccp_send_sms_code.delay(mobile,sms_code)

        # 3、构建响应返回
        return JsonResponse({
            'code': 0,
            'errmsg': 'ok'
        })